<template>
  <div>
    <h3>教学设施设备</h3>
    <div class="container">
      <vxe-toolbar>
        <template #buttons>
          <el-row type="flex" :gutter="10" justify="space-between">
            <el-col :span="5" style="display: flex;">
              <el-button type="success" icon="el-icon-plus" size="mini" @click="insertEvent">新增</el-button>
              <el-button type="success" icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
              <el-button type="success" icon="el-icon-printer" size="mini" @click="printEvent">打印</el-button>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.departmentId" size="small" collapse-tags filterable clearable placeholder="选择责任部门">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_regulationDepartment" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.empId" size="small" collapse-tags filterable clearable placeholder="选择管理人员">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row resizable
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="name" title="教学设备名称" sortable></vxe-table-column>
        <vxe-table-column field="serial" title="教学设备编号" sortable></vxe-table-column>
        <vxe-table-column field="number" title="数量" sortable></vxe-table-column>
        <vxe-table-column field="unit" title="单位" sortable></vxe-table-column>
        <vxe-table-column field="purchaseTime" title="购置日期" sortable></vxe-table-column>
        <vxe-table-column field="department" title="责任部门" sortable></vxe-table-column>
        <vxe-table-column field="emp" title="管理人员" sortable></vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="110">
          <template #default="{ row,rowIndex }">
            <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
            <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="insertModal" :title="isInsert?'新增记录':'修改记录'">
      <template #default>
        <el-form ref="insertForm" :rules="rules" :model="insertForm" inline-message label-width="110px">
          <el-form-item label="教学设备名称" prop="name">
            <el-input size="small" v-model="insertForm.name" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="教学设备编号" prop="serial">
            <el-input size="small" v-model="insertForm.serial" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input size="small" v-model.number="insertForm.number" type="number" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input size="small" v-model="insertForm.unit" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="购置日期" prop="purchaseTime">
            <el-date-picker size="small" type="date" placeholder="选择日期" v-model="insertForm.purchaseTime" style="width: 200px;"></el-date-picker>
          </el-form-item>
          <el-form-item label="管理人员" prop="empId">
            <el-select v-model="insertForm.empId" size="small" collapse-tags filterable clearable placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input size="small" v-model="insertForm.memo" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {currentRoleEmployee,regulation_department} from '@/api/dict.js'
  import {educationFacilities_all,educationFacilities_select,educationFacilities_insert,educationFacilities_update,educationFacilities_delete} from '@/api/organization.js'
  export default {
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        isInsert: true,
        dict_emp: {},
        dict_regulationDepartment: {},
        searchForm: {
          departmentId: '',
          empId: '',
        },
        insertForm: {
          name: '',
          serial: '',
          number: '',
          unit: '',
          purchaseTime: '',
          empId: '',
          memo: '',
        },
        rules: {
          name: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          purchaseTime: [{
            required: true,
            message: '这是必填项',
            trigger: 'change'
          }, ],
        },
        instrumentId: '',
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getGroundAll()
      })
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          educationFacilities_delete({
            instrumentId: row.instrumentId
          }).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.instrumentId == row.instrumentId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        this.insertForm.name = row.name
        this.insertForm.serial = row.serial
        this.insertForm.number = row.number
        this.insertForm.unit = row.unit
        if(this.dict_emp[row.empId]) {
          this.insertForm.empId = row.empId+''
        }else{
          this.insertForm.empId = ''
        }
        this.insertForm.purchaseTime = row.purchaseTime
        this.insertForm.memo = row.memo
        this.insertModal = true
        this.isInsert = false
        this.instrumentId = row.instrumentId
      },
      searchSubmit() {
        let data = {}
        if(this.searchForm.departmentId) data.departmentId = this.searchForm.departmentId
        if(this.searchForm.empId) data.empId = this.searchForm.empId
        educationFacilities_select(data).then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          empId: '',
          departmentId: '',
        }
        this.getGroundAll()
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if(valid) {
            let data = {}
            if(this.insertForm.name) data.name = this.insertForm.name
            if(this.insertForm.serial) data.serial = this.insertForm.serial
            if(this.insertForm.number) data.number = this.insertForm.number
            if(this.insertForm.unit) data.unit = this.insertForm.unit
            if(this.insertForm.purchaseTime) data.purchaseTime = this.$moment(this.insertForm.purchaseTime).format('YYYY-MM-DD')+' 00:00:00'
            if(this.insertForm.empId) data.empId = this.insertForm.empId
            if(this.insertForm.memo) data.memo = this.insertForm.memo
            if(this.isInsert) {
              educationFacilities_insert(data).then(res=>{
                if(res.code === 200) {
                  this.insertSuccess = true
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('添加成功！')
                  this.insertModal = false
                }else{
                  this.$message.error(res.message)
                }
              })
            }else{
              data.instrumentId = this.instrumentId
              educationFacilities_update(data).then(res=>{
                if(res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.instrumentId==item.instrumentId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功！')
                  this.insertModal = false
                }else{
                  this.$message.error(res.message)
                }
              })
            }
          }else{
            return false
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          name: '',
          serial: '',
          number: '',
          unit: '',
          purchaseTime: '',
          empId: '',
          memo: '',
        }
        this.insertModal = true
        this.isInsert = true
        if(this.$refs.insertForm){
          this.$refs.insertForm.resetFields()
        }
      },
      exportData() {
        this.$refs.XTable.exportData({
          filename: this.$route.meta.title, type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>教学设施设备</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '教学设施设备',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      getGroundAll() {
        educationFacilities_all().then(res=>{
          if (res.code === 200 && res.data.length != 0) {
              this.init_data(res.data)
            } else {
              this.defaultDataList = []
            }
          }).then(() => {
            this.findList()
          })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.emp = this.dict_emp[item.empId]
          item.number = item.number==0?'':item.number
          item.department = this.dict_regulationDepartment[item.departmentId]
          item.purchaseTime = this.$moment(item.purchaseTime).format('YYYY-MM-DD')
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          regulation_department().then(res=>{
            this.dict_regulationDepartment = res
          })
          currentRoleEmployee().then(res=>{
            this.dict_emp = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[0])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.container{
  background-color: #FFFFFF;
  padding: 10px;
}
</style>
